#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <memory>
#include <random>
#include <mutex>
#include "../Common/Log.hpp"
struct UserData
{
    std::string _user;
    std::string _password;
    UserData(const std::string &user, const std::string &password)
        : _user(user),
          _password(password)
    {
    }
};
class Session
{
private:
    uint64_t _sessionid;
    std::unordered_map<uint64_t, UserData*> _tables;
    std::mutex _mtx;

public:
    Session()
    {
    }
    ~Session()
    {
    }
    bool HasSessionId(uint64_t sessionid)
    {
        auto iter = _tables.find(sessionid);
        if (iter == _tables.end())
        {
            LOG(DEBUG, "本次登录请求携带的sessionid不存在!\n");
            return false;
        }
        return true;
    }
    uint64_t GetSessionId()
    {
        std::lock_guard<std::mutex> lock(_mtx);
        std::random_device rd;
        std::mt19937 gen(rd());
        // 创建分布，例如生成 1e5 到 1e7 之间的整数
        std::uniform_int_distribution<> dis(1e5, 1e7);
        return dis(gen);
    }
    uint64_t SetNewSessionId(const std::string &user, const std::string &password)
    {
        uint64_t id = GetSessionId();
        //这里不能使用指针指针!
        UserData* obj = new UserData(user,password);
        if(!HasSessionId(id))
        {
            _tables.insert(std::make_pair(id,obj));
            LOG(DEBUG,"新增一个sessionid : %u\n",id);
            return id;
        }
        return -1;
    }
    uint64_t Detect(const std::string& user,const std::string& password,uint64_t id = -1)
    {
        if(!HasSessionId(id))
        {
            //不存在
            uint64_t id = SetNewSessionId(user,password);
            std::cout<<"id : "<<id<<std::endl;
            return id;
        }
        else 
        {
            //TODO
            return -1;
        }
    }
};